//
//  LTChatManager.m
//  LTIM
//
//  Created by 俊松何 on 2017/4/14.
//  Copyright © 2017年 俊松何. All rights reserved.
//

#import "LTChatManager.h"
#import "LTHTTPTool.h"
#import "LTDBHelper.h"
#import "LTSendMessageModel.h"
#import "CGITask.h"
#import "NetworkService.h"
#import "LTSendMessageHelper.h"
#import "LTClient.h"
#import "LTContactManager.h"
@interface  LTChatManager()

@end

@implementation LTChatManager



-(void)sendMessage:(LTMessage *)message
          progress:(void(^)(int progress))progressBlock
        completion:(void(^)(LTMessage *message,LTError *error))completionBlock
{
    
    message.status = LTMessageStatusDelivering;  //设置消息状态
    
    if(message.messageType != LTMessageTypeCMD &&  message.chatType != LTChatTypeChatRoom){
        [[LTDBHelper sharedbhelper] AddMessage:message];
    }
    
    void(^update)(LTMessage *message,LTError *error) = ^(LTMessage *message,LTError *error)
    {
         completionBlock(message,error);
    
    };
    
    switch (message.messageType) {
        case LTMessageTypeText:
        case LTMessageTypeLocation:
        case LTMessageTypeRedBao:
        case LTMessageTypeCreateGroup:
        case LTMessageTypeaddGroupMember:
        case LTMessageTypeaddGroupQRMember:
        case LTMessageTypedeleteGroupMember:
        case LTMessageTypechangeGroupName:
        case LTMessageTypechangeGroupnotice:
        case LTMessageTypeRECEIVERedBao:
        case LTMessageTypeShareGzh:
        case LTMessageTypeLink:
        case LTMessageTypeBigBq:
        case LTMessageTypeCallTip:
        case LTMessageTypePersonCard:
        case LTMessageTypeLuckMoney:
        case LTMessageTypeAtText:
        case LTMessageTypeETHTransfer:
        case LTMessageTypeScreenShots:
        case LTMessageTypeSayhello:
        case LTMessageTypeGift:
        case LTMessageTypeBarrage:
        case LTMessageTypeLightUp:
        case LTMessageTypeCloseLive:
        case LTMessageTypeRoomNormal:               //直播间普通文本消息
        case LTMessageTypeRoomJoin:                 //进入直播间消息
        case LTMessageTypeRoomFocusHost:            //关注主播消息
        case LTMessageTypeRoomSetManager:           //设置为管理员
        case LTMessageTypeRoomCancelManager:        //取消管理员
        case LTMessageTypeRoomMute:                 //禁言用户
        case LTMessageTypeRoomCancelMute:           //取消禁言
        case LTMessageTypeRoomKickout:
        case LTMessageTypeRoomUpdateTitle:
            [[LTSendMessageHelper helper] sendMessage:message completion:update]; break;
        case LTMessageTypeImage: [self _sendImageMessage:message progress:progressBlock completion:update];break;
        case LTMessageTypeVoice: [self _sendVoiceMessage:message progress:progressBlock completion:update]; break;
        case LTMessageTypeVideo: [self _sendVideoMessage:message progress:progressBlock completion:update]; break;
        case LTMessageTypeCMD: [[LTSendMessageHelper helper] sendCmdMessage:message completion:update]; break;
        default:break;
    }
}

-(void)transfromMessage:(LTMessage *)message
             completion:(void(^)(LTMessage *message,LTError *error))completionBlock
{
    message.status = LTMessageStatusDelivering;  //设置消息状态
    [[LTDBHelper sharedbhelper] AddMessage:message];
    void(^update)(LTMessage *message,LTError *error) = ^(LTMessage *message,LTError *error)
    {
        [self updateMessage:message completion:nil];
        completionBlock(message,error);
    };
    [[LTSendMessageHelper helper] sendMessage:message completion:update];
    

}

//发送图片消息
-(void)_sendImageMessage:(LTMessage *)message
                progress:(void(^)(int progress))progressBlock
              completion:(void(^)(LTMessage *message,LTError *error))completionBlock
{
    
    LTMessageImageBody *body = (LTMessageImageBody *)message.body;
    NSData *data =  [NSData dataWithContentsOfFile:body.orginLocalPath];
    [[LTHTTPTool shareTool] uploadImageData:data progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        progressBlock(((CGFloat)totalByteSent / (CGFloat)totalBytesExpectedToSend) * 100);
    } success:^(NSString *remotePath,LTFileTokenModel *ossmodel) {
        body.orginRemotePath = remotePath;
        body.thumbnaildownloadStatus = LTDownloadStatusSuccessed;
        body.orginImagedownloadStatus = LTDownloadStatusSuccessed;
        body.ossModel = ossmodel;
        NSLog(@"%@",remotePath);
        [[LTSendMessageHelper helper] sendMessage:message completion:completionBlock];
    } failer:^(LTError *lterror) {
        message.status =  LTMessageStatusFailed;
        body.thumbnaildownloadStatus = LTDownloadStatusSuccessed;
        body.orginImagedownloadStatus = LTDownloadStatusSuccessed;
        [[LTDBHelper sharedbhelper] updateMessage:message completion:nil];
        completionBlock(message,lterror);
    }];
    
}
//发送语音消息
-(void)_sendVoiceMessage:(LTMessage *)message
                progress:(void(^)(int progress))progressBlock
              completion:(void(^)(LTMessage *message,LTError *error))completionBlock
{
    LTMessageVoiceBody *body = (LTMessageVoiceBody *)message.body;
    NSData *data =  [NSData dataWithContentsOfFile:body.localPath];
    [[LTHTTPTool shareTool] uploadFileData:data FileType:FileTypeVoice progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        progressBlock(((CGFloat)totalByteSent / (CGFloat)totalBytesExpectedToSend) * 100);
    } success:^(NSString *fileUrl,LTFileTokenModel *ossmodel) {
        body.remotePath = fileUrl;
        body.ossModel = ossmodel;
        body.downloadStatus = LTDownloadStatusSuccessed;
        [[LTSendMessageHelper helper] sendMessage:message completion:completionBlock];
        
    } failer:^(LTError *lterror) {
        message.status =  LTMessageStatusFailed;
        body.downloadStatus = LTDownloadStatusSuccessed;
        [[LTDBHelper sharedbhelper] updateMessage:message completion:nil];
        completionBlock(message,lterror);
    }];
    
    
}

//发送视频消息
-(void)_sendVideoMessage:(LTMessage *)message
                progress:(void(^)(int progress))progressBlock
              completion:(void(^)(LTMessage *message,LTError *error))completionBlock
{
    LTMessageVideoBody *body = (LTMessageVideoBody *)message.body;
    NSData *videoData = [NSData dataWithContentsOfFile:body.localvideoPath];
    NSData *coverData = [NSData dataWithContentsOfFile:body.localvideoCoverPath];
    
    __block BOOL videosuc = NO;
    __block BOOL coversuc = NO;
    
    [[LTHTTPTool shareTool] uploadFileData:videoData FileType:FileTypeVideo progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        progressBlock(((CGFloat)totalByteSent / (CGFloat)totalBytesExpectedToSend) * 100);
    } success:^(NSString *fileUrl,LTFileTokenModel *ossmodel) {
        
        videosuc = YES;
        body.remotevideoPath = fileUrl;
        body.videoossModel = ossmodel;
        if(coversuc)
        {
            [[LTSendMessageHelper helper] sendMessage:message completion:completionBlock];
            
        }
        
    } failer:^(LTError *lterror) {
        message.status =  LTMessageStatusFailed;
        completionBlock(message,lterror);
    }];
    
    
    [[LTHTTPTool shareTool] uploadFileData:coverData FileType:FileTypeNormal progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        
    } success:^(NSString *fileUrl,LTFileTokenModel *ossmodel) {
        body.remotevideoCoverPath = fileUrl;
        body.coverossModel = ossmodel;
        coversuc = YES;
        if(videosuc)
        {
             [[LTSendMessageHelper helper] sendMessage:message completion:completionBlock];;
        }
    } failer:^(LTError *lterror) {
        message.status =  LTMessageStatusFailed;
        completionBlock(message,lterror);
    }];
}


-(void)addDelegate:(id<LTChatManagerDelegate>)deleagte
{
    
    [self.chatMangerdelegateArray addObject:deleagte];
    
}

-(void)removeDelegate:(id<LTChatManagerDelegate>)delegate
{
    [self.chatMangerdelegateArray removeObject:delegate];
}

/**
 得到指定类型的小红点数量
 
 @param type  小红点消息类型
 @return 数量
 */
-(NSInteger)getRedDotNumberWithType:(LTNoticeMessageType)type
{
   return  [[LTDBHelper sharedbhelper] getUnradNoticeMessageWithType:type];

}

/**
 添加指定类型的小红点
 
 @param type 小红点消息类型
 @return 操作成功没有
 */
-(BOOL)addRedDotWithType:(LTNoticeMessageType)type
{
    BOOL res =    [[LTDBHelper sharedbhelper] addNoticeMessageWithType:type];
    
    if(res){
        for (id<LTChatManagerDelegate> chatmanger in self.chatMangerdelegateArray) {
            if(chatmanger && [chatmanger respondsToSelector:@selector(redDotMessageUnmberChange)]){
                [chatmanger redDotMessageUnmberChange];
            }
        }
    }

    return res;;
}

/**
 删除指定类型的小红点
 
 @param type 小红点消息类型
 @return 操作成功没有
 */
-(BOOL)deleteRedDotWithType:(LTNoticeMessageType)type
{
   BOOL res =  [[LTDBHelper sharedbhelper] deleteNoticeMessageWithType:type];
    
    if(res){
        for (id<LTChatManagerDelegate> chatmanger in self.chatMangerdelegateArray) {
            if(chatmanger && [chatmanger respondsToSelector:@selector(redDotMessageUnmberChange)]){
                [chatmanger redDotMessageUnmberChange];
            }
        }
    }
    return res;;
}



//更据conversationId获取会话详情
-(LTConversation *)getConversation:(NSString *)conversationId
                            ltuser:(LTUser *)ltuser
                              type:(LTChatType)type
                  createIfNotExist:(BOOL)aifCreate;
{
    if(conversationId == nil)
    {
        return nil;
    }
    LTConversation *conversation = [[LTDBHelper sharedbhelper] getConversationWithConversationID:conversationId];
    if(conversation == nil && aifCreate)
    {
        if(type == LTChatTypeChat)
        {
           if(![[LTClient sharedClient].contactManager isFriendWithUserId:conversationId])
           {
               return nil;
           }
        }
        conversation = [[LTConversation alloc] init];
        conversation.conversationId =   conversationId;
        conversation.conversationUser = ltuser;
        conversation.chatType = type;
        conversation.lastMsgTime = [NSString stringWithFormat:@"%lf",[[NSDate date] timeIntervalSince1970]];
        [[LTDBHelper sharedbhelper] AddConversation:conversation];
        return conversation;
    }
    return conversation;
}
-(NSArray *)getAllConversations
{
    return [[LTDBHelper sharedbhelper] getAllConversation];
}
- (void)deleteConversation:(NSString *)ConversationId
          isDeleteMessages:(BOOL)IsDeleteMessages
                completion:(void (^)(NSString *aConversationId, LTError *lterror))CompletionBlock
{
 
    BOOL res = [[LTDBHelper sharedbhelper] DeleteConversationWithConversationID:ConversationId deleteMessage:IsDeleteMessages];
    if(res)
    {
        CompletionBlock(ConversationId,nil);
    }else
    {
        LTError *lterror = [LTError errorWithDescription:@"删除错误" code:-1];
        CompletionBlock(ConversationId,lterror);
    }
    
}

- (BOOL)insertMessage:(LTMessage *)Message
{
   return  [[LTDBHelper sharedbhelper] AddMessage:Message];
}



- (BOOL)deleteMessage:(LTMessage *)Message
{
    return [[LTDBHelper sharedbhelper] deleteMessageWithMessageId:Message.messageId];
}

- (void)updateMessage:(LTMessage *)Message
           completion:(void (^)(LTMessage *aMessage, LTError *aError))CompletionBlock
{
    [[LTDBHelper sharedbhelper] updateMessage:Message completion:CompletionBlock];
    
    for (id<LTChatManagerDelegate> chatmanger in self.chatMangerdelegateArray) {
        if(chatmanger && [chatmanger respondsToSelector:@selector(didMessageStatusChanged:error:)]){
            [chatmanger didMessageStatusChanged:Message error:nil];
        }
    }
}

- (void)downloadMessageThumbnail:(LTMessage *)Message
                        progress:(void (^)(int progress))ProgressBlock
                      completion:(void (^)(LTMessage *message, LTError *error))CompletionBlock
{
    



}

/**
  SDK会自动下载语音消息，所以除非自动下载语音失败，用户不需要自动下载语音附件
 
 @param Message              消息
 @param ProgressBlock        附件下载进度回调block
 @param CompletionBlock      下载完成回调block
 */
- (void)downloadVoiceMessageAttachment:(LTMessage *)Message
                         progress:(void (^)(int progress))ProgressBlock
                       completion:(void (^)(LTMessage *message, LTError *error))CompletionBlock
{
    LTMessageVoiceBody *body =(LTMessageVoiceBody *) Message.body;
    
    [[LTHTTPTool shareTool] downloadFile:body.remotePath suffix:@"amr" progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        ProgressBlock(((CGFloat)totalByteSent / (CGFloat)totalBytesExpectedToSend) * 100);
    } success:^(NSData *data) {
        [body saveData:data];
        body.downloadStatus = LTDownloadStatusSuccessed;
        [self updateMessage:Message completion:CompletionBlock];
    } failer:^(LTError *lterror) {
        body.downloadStatus = LTDownloadStatusFailed;
        [self updateMessage:Message completion:CompletionBlock];
    }];
    
    
//    [[LTHTTPTool shareTool] downloadVoiceData:body.ossModel progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//
//    } success:^(NSData *data) {
//
//    } failer:^(LTError *lterror) {
//
//    }];
}


- (void)downloadImageMessageAttachment:(LTMessage *)Message
                              progress:(void (^)(int progress))ProgressBlock
                           isthumbnail:(BOOL)isthumbnail
                            completion:(void (^)(LTMessage *message, LTError *error))CompletionBlock
{
    
      LTMessageImageBody *body = (LTMessageImageBody *)Message.body;
        NSString *imageUrl = nil;
        
        if(isthumbnail){
           
            imageUrl = body.thumbnailRemotePath;
        }else
        {
            imageUrl = body.orginRemotePath;
        }
        
        [[LTHTTPTool shareTool] downloadFile:imageUrl suffix:@"jpg" progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            
        } success:^(NSData *data) {
            if(isthumbnail){
                body.thumbnaildownloadStatus = LTDownloadStatusSuccessed;
                [body saveThumbnailimageData:data];
            }else
            {
                body.orginImagedownloadStatus = LTDownloadStatusSuccessed;
                [body saveOrginImageData:data];
            }
            [[LTDBHelper sharedbhelper] updateMessage:Message completion:nil];
            CompletionBlock(Message,nil);
            
            
        } failer:^(LTError *lterror) {
            if(isthumbnail){
                body.thumbnaildownloadStatus = LTDownloadStatusFailed;
            }else{
                body.orginImagedownloadStatus = LTDownloadStatusFailed;
            }
            [[LTDBHelper sharedbhelper] updateMessage:Message completion:nil];
            CompletionBlock(Message,nil);
        }];
    
}
- (void)downloadVideoMessageAttachment:(LTMessage *)Message
                              progress:(void (^)(int progress))ProgressBlock
                            completion:(void (^)(LTMessage *message, LTError *error))CompletionBlock
{
     LTMessageVideoBody *body = (LTMessageVideoBody *)Message.body;
    [[LTHTTPTool shareTool] downloadFile:body.remotevideoPath suffix:@"mp4" progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        ProgressBlock(((CGFloat)totalByteSent / (CGFloat)totalBytesExpectedToSend) * 100);
    } success:^(NSData *data) {
        body.videodownloadStatus = LTDownloadStatusSuccessed;
        [body saveVideoData:data];
        [[LTDBHelper sharedbhelper] updateMessage:Message completion:nil];
        CompletionBlock(Message,nil);
    } failer:^(LTError *lterror) {
        body.videodownloadStatus = LTDownloadStatusFailed;
        [[LTDBHelper sharedbhelper] updateMessage:Message completion:nil];
        CompletionBlock(Message,lterror);
    }];
    
}

/**
 下载视频封面图
 
 @param Message 消息
 @param ProgressBlock   视频下载进度
 @param CompletionBlock 下载完成回调block
 */
- (void)downloadVideoCoverMessageAttachment:(LTMessage *)Message
                                   progress:(void (^)(int progress))ProgressBlock
                                 completion:(void (^)(LTMessage *message, LTError *error))CompletionBlock
{
    
    LTMessageVideoBody *body = (LTMessageVideoBody *)Message.body;
    
    NSString *thumbnail =  @"?imageView&thumbnail=200x200";
    NSString *file = [NSString stringWithFormat:@"%@%@",body.remotevideoCoverPath,thumbnail];
    
    [[LTHTTPTool shareTool] downloadFile:file suffix:@"jpg" progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        ProgressBlock(((CGFloat)totalByteSent / (CGFloat)totalBytesExpectedToSend) * 100);
    } success:^(NSData *data) {
        [body saveCoverimageData:data];
        body.thumbnaildownloadStatus = LTDownloadStatusSuccessed;
        [self updateMessage:Message completion:CompletionBlock];
    } failer:^(LTError *lterror) {
        body.thumbnaildownloadStatus = LTDownloadStatusFailed;
        [self updateMessage:Message completion:CompletionBlock];
    }];
    
    
}

- (void)downloadFileMessageAttachment:(LTMessage *)Message
                             progress:(void (^)(int progress))ProgressBlock
                           completion:(void (^)(LTMessage *message, LTError *error))CompletionBlock;
{
    LTMessageFileBody *body = (LTMessageFileBody *)Message.body;
    
    NSArray *tempArray = [body.remoteFilePath componentsSeparatedByString:@"."];
    NSString *sufix = @"";
    
    if(tempArray.count >=1)
    {
        sufix = tempArray.lastObject;
    }
    [[LTHTTPTool shareTool] downloadFile:body.remoteFilePath suffix:sufix progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        ProgressBlock(((CGFloat)totalByteSent / (CGFloat)totalBytesExpectedToSend) * 100);
    } success:^(NSData *data) {
        body.downloadStatus = LTDownloadStatusSuccessed;
        [body saveData:data];
        [[LTDBHelper sharedbhelper] updateMessage:Message completion:nil];
        CompletionBlock(Message,nil);
    } failer:^(LTError *lterror) {
        body.downloadStatus = LTDownloadStatusFailed;
        [[LTDBHelper sharedbhelper] updateMessage:Message completion:nil];
        CompletionBlock(Message,lterror);
    }];
    
}

/**
 翻译语音消息
 
 @param message    文本消息
 @param completionBlock 翻译完成的回调
 */
-(void)translateMessage:(LTMessage *)message
             tolanguage:(NSString *)tolanguage
             completion:(void(^)(LTMessage *message,LTError *error))completionBlock
{
    if(message.messageType == LTMessageTypeText)
    {
        LTMessageTextBody *body  = (LTMessageTextBody *)message.body;
        
        [[LTHTTPTool shareTool] translateWith:body.text to:tolanguage result:^(NSString *result, LTError *error) {
            if(error == nil)
            {
                message.transContent = result;
                [[LTDBHelper sharedbhelper] updateMessage:message completion:nil];
                
                for (id<LTChatManagerDelegate> chatmanger in self.chatMangerdelegateArray) {
                    if(chatmanger && [chatmanger respondsToSelector:@selector(didMessageStatusChanged:error:)]){
                        [chatmanger didMessageStatusChanged:message error:nil];
                    }
                }
            }
            completionBlock(message,error);
        }];
    }else
    {
        completionBlock(message,[LTError errorWithDescription:@"消息类型错误" code:-1]);
    }
}

-(void)translateWithContent:(NSString *)content
                 tolanguage:(NSString *)tolanguage
                 completion:(void(^)(NSString *result,LTError *error))completionBlock
{
    [[LTHTTPTool shareTool] translateWith:content to:tolanguage result:completionBlock];
    
}



-(NSMutableArray *)chatMangerdelegateArray
{
    if(_chatMangerdelegateArray == nil)
    {
        _chatMangerdelegateArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _chatMangerdelegateArray;
}


@end
